package com.xxg.fileshand.activity

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.rscja.deviceapi.entity.UHFTAGInfo
import com.rscja.team.qcom.deviceapi.F
import com.xxg.fileshand.R
import com.xxg.fileshand.app.App
import com.xxg.fileshand.app.SetInfo
import com.xxg.fileshand.base.BaseVMActivity
import com.xxg.fileshand.base.NoViewModel
import com.xxg.fileshand.base.ext.clickWithTrigger
import com.xxg.fileshand.base.ext.dataConvert
import com.xxg.fileshand.base.ext.getApiService
import com.xxg.fileshand.base.launch
import com.xxg.fileshand.bean.PDRequest
import com.xxg.fileshand.bean.PDTaskRequest
import com.xxg.fileshand.bean.PDTaskRequest.ObjResultDTO
import com.xxg.fileshand.bean.RequestTagBean
import com.xxg.fileshand.constant.Constant
import com.xxg.fileshand.databinding.ActivityGoodsInventoryBinding
import com.xxg.fileshand.databinding.ItemInventoryHeaderBinding
import com.xxg.fileshand.greendao.FilesInfoDTO
import com.xxg.fileshand.greendao.GreenDaoManager
import com.xxg.fileshand.greendao.OfflineRequestDTO
import com.xxg.fileshand.pop.PopBorrowOrReturn
import com.xxg.fileshand.pop.PopTagList
import com.xxg.fileshand.reader.ReaderUtils
import com.xxg.fileshand.type.OperateType
import java.io.File
import java.util.*

class GoodsInventoryActivity : BaseVMActivity<ActivityGoodsInventoryBinding, NoViewModel>() {

    private var caseCode: String = ""
    private var caseName: String = ""

    private var canRead = true

    private var originList = mutableListOf<FilesInfoDTO>()
    private var originTidList = mutableListOf<String>() //原始的tid列表
    private var readTidList = mutableListOf<String>() //读取到的所有tid列表
    private var wrongTidList = mutableListOf<String>() //错架的tid列表
    private var borrowTidList = mutableListOf<String>() //外借的tid列表

    var headerBinding: ItemInventoryHeaderBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        if (caseCode == "") {
//            toast("层位码为空")
//            finish()
//            return
//        }
        showRightText("重读")

        initFilesAdapter()
        val headerView = View.inflate(this, R.layout.item_inventory_header, null)
        headerBinding = ItemInventoryHeaderBinding.bind(headerView)
        filesAdapter.addHeaderView(headerView)
        headerBinding?.rlInCase?.clickWithTrigger {
            if (headerBinding?.tvInCase?.text == "0") {
                return@clickWithTrigger
            }
            val x = mutableListOf<String>()
            x.addAll(getReadNoWrongList())
            x.removeAll(borrowTidList)
            //originList.filter { x.contains(it.eid) }
            XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .asCustom(
                    PopTagList(
                        mContext,
                        originList.filter { x.contains(it.eid) }.toMutableList()
                    )
                ).show()
        }
        headerBinding?.rlWaitRead?.clickWithTrigger {
            if (headerBinding?.tvWaitRead?.text == "0") {
                return@clickWithTrigger
            }
            val x = mutableListOf<String>()
            x.addAll(originTidList)
            x.removeAll(getReadNoWrongList())
            //originList.filter { x.contains(it.eid) }
            XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .asCustom(
                    PopTagList(
                        mContext,
                        originList.filter { x.contains(it.eid) }.toMutableList()
                    )
                ).show()
        }
        headerBinding?.rlWrongCase?.clickWithTrigger {
            if (headerBinding?.tvWrongCase?.text == "0") {
                return@clickWithTrigger
            }
            val x = mutableListOf<FilesInfoDTO>()
            x.addAll(filesList)
            x.addAll(originList)
            //originList.filter { x.contains(it.eid) }
            XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .asCustom(
                    PopTagList(
                        mContext,
                        x.filter { wrongTidList.contains(it.eid) }.toMutableList()
                    )
                ).show()
        }
        headerBinding?.rlOutCase?.clickWithTrigger {
            if (headerBinding?.tvOutCase?.text == "0") {
                return@clickWithTrigger
            }
            val x = mutableListOf<FilesInfoDTO>()
            x.addAll(filesList)
            x.addAll(originList)
            //originList.filter { x.contains(it.eid) }
            XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .asCustom(
                    PopTagList(
                        mContext,
                        x.filter { borrowTidList.contains(it.eid) }.toMutableList()
                    )
                ).show()
        }

//        if (SetInfo.isOffline()) {
//            GreenDaoManager.findWzInfoDTOListInCase(caseCode)?.let {
//                headerBinding?.tvInCase?.text = "0"
//                headerBinding?.tvWaitRead?.text = it.size.toString()
//                originList.addAll(it)
//                filesList.addAll(it)
//                originTidList.addAll(originList.map { it.tid })
//                filesAdapter?.notifyDataSetChanged()
//            } ?: "$caseCode 档案信息为空！"
//        } else {
//            launch({
//                val wzRp = getApiService().searchWZ(
//                    mapOf(
//                        "szSearch" to caseCode,
//                        "nType" to 2,
//                        "nArchivesType" to 1,
//                        "nStaffID" to App.nStaffID
//                    )
//                )
//                if (wzRp.result > 0 && wzRp.row > 0) {
//                    val inList = wzRp.wZinfos.filter { it.szStateName == "在馆" }
//                    if (inList.isNotEmpty()) {
//                        headerBinding?.tvInCase?.text = "0"
//                        headerBinding?.tvWaitRead?.text = inList.size.toString()
//                        originList.addAll(inList)
//                        filesList.addAll(inList)
//                        originTidList.addAll(originList.map { it.tid })
//                        filesAdapter?.notifyDataSetChanged()
//                    } else {
//                        toast("该层位下没有在馆档案")
//                    }
//                } else {
//                    toast("未找到档案")
//                }
//            })
//        }

        switchScan(true)
        initView()
    }

    private fun initView() {

        mBinding.etCaseCode.setOnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftKeyboard()
                val caseCode = textView.text.toString()
                loadCase(caseCode, true)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        mBinding.tvRfid.clickWithTrigger {
            if (ReaderUtils.instance.isScanningRFID.value == true) {
                toast("请先停止扫描")
                return@clickWithTrigger
            }
            if (isScanTMCode) {
                XPopup.Builder(this)
                    .asConfirm(null, "是否切换为RFID模式") {
                        isScanTMCode = false
                        it.text = "RFID模式"
                    }.show()
            } else {
                XPopup.Builder(this)
                    .asConfirm(null, "是否切换为扫码模式") {
                        isScanTMCode = true
                        it.text = "扫码模式"
                    }.show()
            }
        }

        mBinding.btnSave.clickWithTrigger {
            if (ReaderUtils.instance.isScanningRFID.value == true) {
                toast("请先停止盘点！")
                return@clickWithTrigger
            }

            val pdRequest = PDRequest()
            pdRequest.caseCode = caseCode
            pdRequest.reqId = UUID.randomUUID().toString()
            pdRequest.deviceId = DeviceUtils.getUniqueDeviceId()
            pdRequest.onCount = (headerBinding?.tvInCase?.text ?: "0").toString()
            pdRequest.outCount = (headerBinding?.tvWaitRead?.text ?: "0").toString()
            pdRequest.errorCount = (headerBinding?.tvWrongCase?.text ?: "0").toString()
            pdRequest.lendingCount = (headerBinding?.tvOutCase?.text ?: "0").toString()
            pdRequest.reqCaseCheckDetailVos = mutableListOf()
            val waitTidList = mutableListOf<String>()
            waitTidList.addAll(originTidList)
            readTidList.forEach { tid ->
                val dto = PDRequest.ReqCaseCheckDetailVosDTO()
                var filesInfoDTO = filesList.find { tid == it.eid }
                if (filesInfoDTO == null) {
                    filesInfoDTO = originList.find { it.eid == tid }
                }
                filesInfoDTO?.let {
                    dto.daCode = filesInfoDTO.daCode
                    dto.daName = filesInfoDTO.daName
                    dto.caseCode = filesInfoDTO.caseCode
                    dto.currentCaseCode = caseCode
                    if (wrongTidList.contains(tid)) {
                        dto.status = "5"
                    } else {
                        dto.status = "4"
                    }
                    pdRequest.reqCaseCheckDetailVos.add(dto)
                    if (waitTidList.contains(tid)) {
                        waitTidList.remove(tid)
                    }
                }
            }
            borrowTidList.forEach { tid ->
                val dto = PDRequest.ReqCaseCheckDetailVosDTO()
                var filesInfoDTO = filesList.find { tid == it.eid }
                filesInfoDTO?.let {
                    dto.daCode = it.daCode
                    dto.daName = it.daName
                    dto.caseCode = it.caseCode
                    dto.currentCaseCode = caseCode
                    dto.status = "6"
                    pdRequest.reqCaseCheckDetailVos.add(dto)
                }
            }
//            waitTidList.forEach {
//                val dto = PDRequest.ObjResultDTO()
//                dto.szBookID = it
//                dto.npDstatus = 2
//                pdRequest.objResult.add(dto)
//            }

            if (SetInfo.isOffline()) {
                val offlineRequestDTO = OfflineRequestDTO()
                offlineRequestDTO.requestJson = Gson().toJson(
                    pdRequest
                )
                offlineRequestDTO.requestTime = TimeUtils.getNowMills()
                offlineRequestDTO.requestType = Constant.REQUEST_INVENTORY_WZ
                GreenDaoManager.addOfflineRequestDTO(offlineRequestDTO)
                toast("盘点上传成功")
                onBackPressed()
            } else {
                launch({
                    val emptyResponse = getApiService().checkCheckSave(
                        pdRequest
                    ).dataConvert()
                    if (emptyResponse.result > 0) {
                        toast("盘点上传成功")
                        onBackPressed()
                    } else {
                        toast(emptyResponse.msg)
                    }
                })
            }
        }
    }

    override fun isScan(): Boolean {
        return canRead
    }

    override fun getMyTitle(): String {
        return "档案盘点"
    }

    override fun onLeftClick() {
        onBackPressed()
    }

    override fun onRightClick() {
        if (ReaderUtils.instance.isScanningRFID.value == true) {
            toast("请先停止盘点！")
            return
        }
        clearInventory()
    }

    override fun onEpcRead(tagInfo: UHFTAGInfo) {
        val tid = tagInfo.tid
        if (caseCode.isEmpty()) {
            loadCase(tid)
            return
        }

        if (originTidList.contains(tid)) {//符合需要盘点的列表的才判断是否删除
            try {
                readTidList.add(tid)
                val index = originTidList.indexOf(tid)
                val wzInfoDTO = originList[index]
                if (filesList.contains(wzInfoDTO)) {
                    filesList.remove(wzInfoDTO)
                    filesAdapter.notifyDataSetChanged()
                    refreshInventoryCount()
                }
            } catch (e: Exception) {
                LogUtils.e("onEpcRead出错：${e.message}")
            }
        } else {
            if (readTidList.contains(tid)) {
                return
            }
            if (SetInfo.isOffline()) {
                val wzInfo = GreenDaoManager.findFilesInfoDTO(tid)
                wzInfo?.let {
                    readTidList.add(tid)
                    if (it.caseCode == caseCode) {
                        it.caseCodeTrans = "外借 ${it.caseCodeTrans}"
                        borrowTidList.add(tid)
                        filesList.add(it)
                        filesAdapter.notifyDataSetChanged()
                        refreshInventoryCount()
                    } else {
                        if (!SetInfo.isIgnoreWrongCase()) {
                            it.caseCodeTrans = "错架 ${it.caseCodeTrans}"
                            wrongTidList.add(tid)
                            filesList.add(it)
                            filesAdapter.notifyDataSetChanged()
                            refreshInventoryCount()
                        }
                    }

                }
            } else {
                launch({
                    if (readTidList.contains(tid)) {
                        return@launch
                    }
                    val files = getApiService().guidanceArchiveReq(
                        mapOf(
                            "reqId" to UUID.randomUUID().toString(),
                            "deviceId" to DeviceUtils.getUniqueDeviceId(),
                            "tagList" to listOf(RequestTagBean(tid)),
                        )
                    ).dataConvert()
                    if (files.archiveInfo != null && files.archiveInfo.size > 0) {
                        readTidList.add(tid)
                        val filesInfoDTO = files.archiveInfo[0]
                        if (filesInfoDTO.caseCode == caseCode) {
                            filesInfoDTO.caseCodeTrans = "外借 ${filesInfoDTO.caseCodeTrans}"
                            borrowTidList.add(tid)
                            filesList.add(filesInfoDTO)
                            filesAdapter.notifyDataSetChanged()
                            refreshInventoryCount()
                        } else {
                            if (!SetInfo.isIgnoreWrongCase()) {
                                filesInfoDTO.caseCodeTrans = "错架 ${filesInfoDTO.caseCodeTrans}"
                                wrongTidList.add(tid)
                                filesList.add(filesInfoDTO)
                                filesAdapter.notifyDataSetChanged()
                                refreshInventoryCount()
                            }
                        }

                    }
                }, {
                    LogUtils.e("非盘点任务请求出错Tid：$tid")
                })
            }
        }
    }

    private fun loadCase(tid: String, isCaseCode: Boolean = false) {
        if (SetInfo.isOffline()) {
            (if (isCaseCode) GreenDaoManager.findCaseCodeDTO4CaseCode(tid) else GreenDaoManager.findCaseCodeDTO(
                tid
            ))?.let { caseRp ->
                mBinding.etCaseCode.setText(caseRp.caseCode)
                mBinding.tvCaseTrans.text = caseRp.caseCodeTrans

//                val caseNoList =
//                    caseRp.caseCodeTrans.split("馆", "库房", "区", "列", "面", "节", "层")
//                mBinding.tvGuan.text = caseNoList[0] ?: ""
//                mBinding.tvKufang.text = caseNoList[1] ?: ""
//                mBinding.tvQu.text = caseNoList[2] ?: ""
//                mBinding.tvLie.text = caseNoList[3] ?: ""
//                mBinding.tvMian.text = caseNoList[4] ?: ""
//                mBinding.tvJie.text = caseNoList[5] ?: ""
//                mBinding.tvCeng.text = caseNoList[6] ?: ""
                mBinding.tvConfirmCase.clickWithTrigger { view ->
                    clearList()
                    caseCode = caseRp.caseCode ?: ""
                    mBinding.tvCaseName.text = caseRp.caseCodeTrans
                    GreenDaoManager.findFilesInfoDTOListInCase(caseRp.caseCode)?.let { files ->
                        val inList = files.filter { it.borrowStatus == 3 }.map {
                            it.caseCodeTrans = caseRp.caseCodeTrans
                            it
                        }
                        if (inList.isNotEmpty()) {
                            headerBinding?.tvInCase?.text = "0"
                            headerBinding?.tvWaitRead?.text = inList.size.toString()
                            originList.addAll(inList)
                            filesList.addAll(inList)
                            originTidList.addAll(originList.map { it.eid })
                            filesAdapter?.notifyDataSetChanged()
                        } else {
                            toast("该层位下没有在馆档案")
                        }
                    } ?: "$caseCode 档案信息为空！"
                    ReaderUtils.instance.reset()
                    switchScan(false)
                }
                mBinding.tvConfirmCase.performClick()

            }
        } else {
            launch({
                val caseRp = getApiService().checkCaseCheck(
                    mapOf(
                        "reqId" to UUID.randomUUID().toString(),
                        "deviceId" to DeviceUtils.getUniqueDeviceId(),
                        if (isCaseCode) {
                            "caseCode" to tid
                        } else {
                            "eid" to tid
                        }
                    )
                ).dataConvert()
                mBinding.etCaseCode.setText(caseRp.caseCode)
                mBinding.tvCaseTrans.text = caseRp.caseCodeTrans

                mBinding.tvConfirmCase.clickWithTrigger { view ->
                    clearList()
                    caseCode = caseRp.caseCode ?: ""
//                caseInfo = it
                    mBinding.tvCaseName.text = caseRp.caseCodeTrans
//                mBinding.tvCaseNumCn.text = caseInfo?.caseCodeTrans
                    if (caseRp.archiveInfo != null && caseRp.archiveInfo.size > 0) {
                        //同时将it.caseCodeTrans设置为caseRp.caseCodeTrans
                        val inList = caseRp.archiveInfo.filter { it.borrowStatus == 3 }.map {
                            it.caseCodeTrans = caseRp.caseCodeTrans
                            it
                        }
                        if (inList.isNotEmpty()) {
                            headerBinding?.tvInCase?.text = "0"
                            headerBinding?.tvWaitRead?.text = inList.size.toString()
                            originList.addAll(inList)
                            filesList.addAll(inList)
                            originTidList.addAll(originList.map { it.eid })
                            filesAdapter?.notifyDataSetChanged()
                        } else {
                            toast("该层位下没有在馆档案")
                        }
                    } else {
                        toast("未找到档案")
                    }
                    ReaderUtils.instance.reset()
                    switchScan(false)
                }
                mBinding.tvConfirmCase.performClick()
            }, {
//                toast(it.message)
            })
        }


    }

    private fun clearList() {
        filesList.clear()
        originList.clear()
        originTidList.clear()
    }

    private fun switchScan(isScan: Boolean) {
        if (isScan) {
            ReaderUtils.instance.reset()
            ReaderUtils.instance.setPower(SetInfo.getScanCasePower())
            filesList.clear()
            filesAdapter.notifyDataSetChanged()
            caseCode = ""
//            caseInfo = null
//            mBinding.tvCaseName.text = ""
            mBinding.etCaseCode.setText("")
            mBinding.tvCaseTrans.text = ""
            mBinding.tvGuan.text = ""
            mBinding.tvKufang.text = ""
            mBinding.tvQu.text = ""
            mBinding.tvLie.text = ""
            mBinding.tvMian.text = ""
            mBinding.tvJie.text = ""
            mBinding.tvCeng.text = ""
            mBinding.llScan.visibility = View.VISIBLE
            mBinding.llInventory.visibility = View.GONE
            mBinding.tvRfid.visibility = View.GONE
        } else {
            ReaderUtils.instance.setPower(SetInfo.getScanWzPower())
            mBinding.llScan.visibility = View.GONE
            mBinding.llInventory.visibility = View.VISIBLE
            mBinding.tvRfid.visibility = View.GONE

        }
    }

    private fun clearInventory() {

        mBinding.etCaseCode.setText("")
        mBinding.tvCaseTrans.text = ""
        mBinding.tvGuan.text = ""
        mBinding.tvKufang.text = ""
        mBinding.tvQu.text = ""
        mBinding.tvLie.text = ""
        mBinding.tvMian.text = ""
        mBinding.tvJie.text = ""
        mBinding.tvCeng.text = ""
        mBinding.tvConfirmCase.clickWithTrigger {
        }

        readTidList.clear()
        wrongTidList.clear()
        borrowTidList.clear()
        filesList.clear()
        filesList.addAll(originList)
        filesAdapter.notifyDataSetChanged()
        refreshInventoryCount()
        ReaderUtils.instance.resetData()
    }

    private fun refreshInventoryCount() {
        //将readTidList中包含wrongTidList的部分移除
        val readNoWrongList = mutableListOf<String>()
        readNoWrongList.addAll(readTidList)
        readNoWrongList.removeAll(wrongTidList)

        headerBinding?.tvInCase?.text = (readNoWrongList.size - borrowTidList.size).toString()
        headerBinding?.tvWaitRead?.text =
            if ((originTidList.size - readNoWrongList.size + borrowTidList.size) < 0) "0" else (originTidList.size - readNoWrongList.size + borrowTidList.size).toString()
//            if ((originTidList.size - readNoWrongList.size) < 0) "0" else (originTidList.size - readNoWrongList.size).toString()
        headerBinding?.tvWrongCase?.text = wrongTidList.size.toString()
        headerBinding?.tvOutCase?.text = borrowTidList.size.toString()
    }

    private fun getReadNoWrongList(): MutableList<String> {
        val readNoWrongList = mutableListOf<String>()
        readNoWrongList.addAll(readTidList)
        readNoWrongList.removeAll(wrongTidList)
        return readNoWrongList
    }


}